#include <iostream>
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include "blockQueue.hpp"
#include "Task.hpp"

using namespace std;


//消费者
void* consumer(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    
    while(true)
    {
        sleep(1);
        Task t;
        bq->pop(&t);
        t();

        //结合业务逻辑，处理数据
        cout << pthread_self() <<"res:" << t.formatArg() << t.formatRes() << endl;


    }
}

//生产者
void* productor(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    std::string opers = "+-*/%";
    while(true)
    {
        sleep(1);
        //1.获取数据
        int x = rand() % 20 + 1;
        int y = rand() % 10 + 1;
        char op = opers[rand() % opers.size()];
        //2.将数据推送到阻塞队列
        Task t(x,y,op);
        bq->push(t);
        cout << pthread_self() << " productor Task:" << t.formatArg() << "?" << endl;
    }
    
}

int main()
{
    srand((uint64_t)time(nullptr) ^ getpid());

    BlockQueue<Task>* bq = new BlockQueue<Task>();

    pthread_t c,p;
    pthread_create(&p,nullptr,productor,bq);
    pthread_create(&c,nullptr,consumer,bq);
    


    pthread_join(c,nullptr);
    pthread_join(p,nullptr);

    delete bq;
    return 0;
}